// import Mock from 'mockjs'
import { localStore } from '@/common/utils/storage.js'
import _ from 'lodash'

// const Random = Mock.Random

const add = (product) => {
  let cart = localStore.get('tiny_cart')
  cart = cart || []

  if (cart.length) {
    const prod = _.find(cart, { id: product.id })

    if (prod) {
      prod.count += product.count
    } else {
      cart.unshift(product)
    }
  } else {
    cart.unshift(product)
  }

  localStore.set('tiny_cart', cart)
  return product.id
}

const remove = (productId) => {
  const cart = localStore.get('tiny_cart')

  if (cart && cart.length) {
    _.remove(cart, (prod) => {
      return prod.id === productId
    })
    localStore.set('tiny_cart', cart)
    return productId
  } else {
    return null
  }
}

const removeSome = (productIds) => {
  const cart = localStore.get('tiny_cart')

  if (cart && cart.length) {
    productIds.forEach((productId) => {
      _.remove(cart, (prod) => {
        return prod.id === productId
      })
    })

    localStore.set('tiny_cart', cart)
    return productIds
  } else {
    return null
  }
}

const query = () => {
  return localStore.get('tiny_cart') || []
}

export default {
  add,
  remove,
  removeSome,
  query
}
